package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 申请Token信息
type ClientCredReqMsg struct {
	GrantType            string `json:"grant_type"`
	ClientId             string `json:"client_id"`
	ClientSecret         string `json:"client_secret"`
	ClientCredentialsUrl string `json:"client_credentials_url"`
}

// 申请Token，响应消息
type ClientCredResMsg struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
	TokenType   string `json:"token_type"`
}

type Push struct {
	ValidateOnly bool         `json:"validate_only"`
	Message      *PushMessage `json:"message"`
}

type PushMessage struct {
	Notification *PushNotification `json:"notification"`
	Android      *PushAndroid      `json:"android"`
	Token        []string          `json:"token"`
}

type PushNotification struct {
	Title string `json:"title"`
	Body  string `json:"body"`
}

type PushAndroid struct {
	Notification *PushAndroidNotification `json:"notification"`
}

type PushAndroidNotification struct {
	Title       string           `json:"title"`
	Body        string           `json:"body"`
	ClickAction *PushClickAction `json:"click_action"`
}

type PushClickAction struct {
	Type   int64  `json:"type"`
	Intent string `json:"intent"`
}

// 支付订单信息
type UserPush struct {
	BaseM
	Uid        bson.ObjectId `bson:"_id" json:"_id"`               // 用户uid
	PushToken  string        `bson:"pushToken" json:"pushToken"`   // 手机token
	Platform   int64         `bson:"platform" json:"platform"`     // 平台
	UpdateTime int64         `bson:"updateTime" json:"updateTime"` // 消息更新时间
}

func NewUserPush() cache.EntryI {
	return &UserPush{}
}

func (up *UserPush) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("UserPush", bson.M{"_id": up.Uid}, up)
	return
}

func (up *UserPush) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		up.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		up.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UserPush_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return up.LoadData()
}

func (up *UserPush) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("UserPush", bson.M{"_id": up.Uid}, nil, &up)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

func (up *UserPush) Update(val *UserPush) {
	Cache.Put("UserPush", val.Uid.Hex(), val)
	val.UpdateData()
}

func GetUserPush(uid string) (r *UserPush) {
	v, _ := Cache.Get("UserPush", uid)
	r = v.(*UserPush)
	return
}
